import {Login} from '@/api'
import Vue from 'vue'
import fa from "element-ui/src/locale/lang/fa";

const getDefaultState = () => {
    return {
        name: '',
        userInfo: {}
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        localStorage.clear();
        Object.assign(state, getDefaultState())
    },
    SET_NAME: (state, name) => {
        state.name = name;
        Vue.ls.set("name", name);
    },
    SET_USERINFO: (state, userInfo) => {
        state.userInfo = userInfo;
        Vue.ls.set("userInfo", userInfo);

    },
}

const actions = {
    // 登录
    async login({commit}, userInfo) {
        const result = await Login(userInfo)
        console.log(result)
        if (!result.hasOwnProperty("name")) {
            return Promise.reject(result.msg);
        }
        commit('SET_NAME', userInfo.name);
        return Promise.resolve(result);
    },
    // 退出登录
    logout({commit, state}) {
        return new Promise((resolve, reject) => {
            commit('RESET_STATE')
            resolve()
        })
    },

    // 清除token
    resetToken({commit}) {
        return new Promise(resolve => {
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

